package nbcp.mvc.listener

import nbcp.base.comm.config
import nbcp.base.enums.MyOqlComponentEnum
import nbcp.base.event.HttpRequestEvent
import nbcp.base.extend.*
import nbcp.base.model.HttpFeignLogData
import nbcp.http.event.HttpClientInitEvent
import nbcp.http.event.HttpClientPostEvent
import nbcp.mvc.HttpContext
import org.slf4j.LoggerFactory
import org.springframework.context.event.EventListener

/**
 * 程序的最高事件。
 */
class HttpClientEventListener {
    init {
        config.loadedComponent = config.loadedComponent or MyOqlComponentEnum.MVC.value;
    }


    @EventListener(HttpClientInitEvent::class)
    fun onHttpClientInit(event: HttpClientInitEvent) {
        var http = event.request!!;
        val token = HttpContext.token
        if (token.key.HasValue) {
            logger.info("初始化传递 ${token.key}: ${token.value}")
            http.addHeader(token.key, token.value)
        }


        val xTraceId = HttpContext.xTraceId
        if (xTraceId.HasValue) {
            http.addHeader("X-Trace-Id", xTraceId)
        }
        val xRealIp = HttpContext.clientIp
        if (xRealIp.HasValue) {
            http.addHeader("X-Real-Ip", xRealIp)
        }
    }

    @EventListener(HttpClientPostEvent::class)
    fun onPost(event: HttpClientPostEvent) {
        HttpContext.lastRequest = event.request;
        HttpContext.lastRequestType = event.type;
    }


    @EventListener(HttpRequestEvent::class)
    fun onPost(event: HttpRequestEvent) {
        HttpContext.lastRequest = event.request;
    }


    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }
}